package com.xbongbong.paas.help.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.abstracts.AbstractOperatorFieldHandler;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.DateTimeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.help.factory.OperatorFieldHandler;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.OperationsPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2020/3/4 21:11
 * @since v1.0
 */
@Component
public class OperatorDateTimeHandlerImpl extends AbstractOperatorFieldHandler {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.DATETIME.getType());
    }

    @Override
    public Object handlerTargetFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity, FieldAttrEntity targetField,
                                         BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        // 当目标表单为日期字段而当前表单为日期时间字段，此时将当前表单中日期时间字段件中的日期赋值给目标表单中的日期字段，丢弃时间。
        // 当目标表单为日期时间字段而当前表单为日期字段，此时将当前表单中日期字段中的日期赋值给目标表单中的日期时间字段，时间设置为00:00:00
        String attr = fieldAttrEntity.getAttr();
        if (Objects.equals(targetField.getDateType(), DateTimeEnum.TIME.getType())) {
            Long time = data.getLong(attr);
            if (Objects.equals(0L, time)) {
                return null;
            }
            Long beforeDate = PaasDateUtil.getBeforeDayBreak(data.getLong(attr));
            if (Objects.equals(0L, beforeDate)) {
                return null;
            }
           return beforeDate;
        } else {
           return data.get(attr);
        }
    }

    @Override
    public Object handlerFixedValue(FieldAttrEntity targetField, BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        //
        if (Objects.equals(DateTimeEnum.TIME.getType(), targetField.getDateType())) {
            Long beforeDate = PaasDateUtil.getBeforeDayBreak(Long.valueOf(String.valueOf(operation.getValue())));
            if (Objects.equals(0L, beforeDate)) {
                return null;
            }
            return beforeDate;
        }
        return operation.getValue();
    }


}
